﻿@inherits ComponentBase
@using GMS.NET.Web.Components.Shared.Global.Misc
@using System.Diagnostics.CodeAnalysis
@inject GMS.NET.Web.Components.Service.Interface.System.IImportService Import
@inject DownloadService DownloadService
<Modal @ref="Modal" OnShownAsync="OnShownCallbackAsync">
    @if (IsShowTable)
    {
        <ModalDialog IsDraggable="true" IsScrolling="true" Title="@ModelName">
            <BodyTemplate>
                <Table TItem="DynamicData" OnQueryAsync="OnQueryAsync"
                       IsStriped="true" IsBordered="true" ShowToolbar="true"
                       ShowDefaultButtons="false" ShowEmpty="true" IsPagination="true"
                       PageItemsSource="@(new int[] { 20, 40, 80, 100 })" @ref="Table">
                    <TableToolbarTemplate>
                        <Row ItemsPerRow="ItemsPerRow.Three">
                            <Button Color="Color.Info" IsAsync="true" Icon="fas fa-fw fa-list-check" Text="检验数据" OnClick="@CheckExcel"></Button>
                            <Button Text="检验结果" Color="Color.Secondary" IsAsync="true" Icon="fas  fa-fw fa-cloud-arrow-down" OnClick="@DownCheckExcel" />
                            <Button Color="Color.Success" IsAsync="true" Icon="fas fa-fw fa-database" Text="导入数据" OnClick="@ExcelToDataBase" IsDisabled="!ExcelToDataBaseStatus"></Button>
                        </Row>
                    </TableToolbarTemplate>
                    <TableColumns>
                        <TableColumn @bind-Field="@context.Fix" />
                        <TableColumn Field="@("检验说明")" FieldName="@("检验说明")" Text="@("检验说明")" Sortable="true">
                            <Template Context="v">
                                <div>@v.Value</div>
                            </Template>
                        </TableColumn>
                        <TableColumn Field="@("检验状态")" FieldName="@("检验状态")" Text="@("检验状态")" Sortable="true">
                            <Template Context="v">
                                <div>@v.Value</div>
                            </Template>
                        </TableColumn>
                        @foreach (var element in DynamicColumnList)
                        {
                            <TableColumn Field="@element.ToString()" FieldName="@element.ToString()" Text="@element" Sortable="true">
                                <Template Context="v">
                                    <div>@v.Value</div>
                                </Template>
                            </TableColumn>
                        }
                    </TableColumns>
                </Table>
            </BodyTemplate>
        </ModalDialog>
    }
    else
    {
        <ModalDialog Size="Size.Large" IsDraggable="true" Title="@ModelName">
            <BodyTemplate>
                <Row ItemsPerRow="ItemsPerRow.Two">
                    <Card>
                        <BodyTemplate>
                            <h5 class="card-title">下载模板按钮</h5>
                            <p class="card-text">请使用指定excel模板设置数据,点击下载模板按钮获取标准数据模板.</p>
                            <Button Text="下载模板" IsAsync="true" Icon="fas  fa-fw fa-cloud-arrow-down" OnClick="@DownExcel" />
                        </BodyTemplate>
                    </Card>
                    <Card>
                        <BodyTemplate>
                            <h5 class="card-title">上传数据按钮</h5>
                            <p class="card-text">根据下载的指定模板填充完毕数据后,请点击上传数据选择excel文件双击上传.</p>
                            <ButtonUpload TValue="string" ShowProgress="true" OnChange="@UploadExcel" OnDelete="@(fileName => Task.FromResult(true))" BrowserButtonText="上传数据" BrowserButtonIcon="fas fa-fw fa-cloud-arrow-up"></ButtonUpload>
                        </BodyTemplate>
                    </Card>
                </Row>
            </BodyTemplate>
        </ModalDialog>
    }
</Modal>

@code {
    /// <summary>
    /// 窗口名称
    /// </summary>
    [Parameter]
    public string? ModelName { get; set; }
    /// <summary>
    /// 下载excel模板的名称
    /// </summary>
    [Parameter]
    public string? ExcelTempName { get; set; }
    /// <summary>
    /// 下载的excel模板的请求地址
    /// </summary>
    [Parameter]
    public string? DownExcelTempUrl { get; set; }
    /// <summary>
    /// 数据验证的请求地址
    /// </summary>
    [Parameter]
    public string? DataCheckUrl { get; set; }
    /// <summary>
    /// 数据导入的请求地址
    /// </summary>
    [Parameter]
    public string? DataImportUrl { get; set; }

    /// <summary>
    ///
    /// </summary>
    private Modal? Modal { get; set; }

    /// <summary>
    ///
    /// </summary>
    [Parameter]
    public EventCallback<Modal> ModalChanged { get; set; }

    [NotNull]
    private List<string>? DynamicColumnList { get; set; } = new();

    [NotNull]
    private Table<DynamicData>? Table { get; set; }

    [Inject]
    [NotNull]
    private MessageAlert? MessageService { get; set; }

    private bool IsShowTable = false;

    /// <summary>
    /// OnInitialized
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

    private Task OnShownCallbackAsync()
    {
        IsShowTable = false;
        return Task.CompletedTask;
    }

    private async Task<QueryData<DynamicData>> OnQueryAsync(QueryPageOptions options)
    {
        var Items = new List<DynamicData>();
        var total = 0;
        var search = new QueryPivot();
        search.PageIndex = options.PageIndex;
        search.PageSize = options.PageItems;
        var result = await Import.GetExcelData(search);
        if (result is not null)
        {
            if (result.page_Total > 0)
            {
                var dataItems = result.Items;

                total = result.page_Total;

                for (int i = 0; i < dataItems!.Count; i++)
                {
                    Items.Add(new DynamicData((i + 1).ToString(), dataItems[i]));
                }
            }
        }

        // sort logic ...
        // filter logic ...

        return new QueryData<DynamicData>()
        {
            Items = Items,
            TotalCount = total,
            IsSorted = true,
            IsFiltered = true
        };
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 渲染成功后将参数传递给父组件
            await ModalChanged.InvokeAsync(Modal);
        }
    }

    private bool ExcelToDataBaseStatus = false;

    private async Task UploadExcel(UploadFile uploadFile)
    {
        using var stream = uploadFile.File!.OpenReadStream();
        var dycCols = await Import.UploadExcelData(stream);
        if (dycCols is not null)
        {
            DynamicColumnList = dycCols.Where(x => !new List<string>() { "检测说明", "检测状态" }.Any(y => y == x)).ToList();
            IsShowTable = true;
            StateHasChanged();
        };
    }

    private async Task DownExcel()
    {
        if (string.IsNullOrWhiteSpace(DownExcelTempUrl))
        {
            await MessageService.Warning("请输入模板下载地址");
            return;
        }
        var Stream = await Import.GetExcelTemp(DownExcelTempUrl!);
        if (Stream is not null) await DownloadService.DownloadFromStreamAsync($"{ExcelTempName}.xlsx", Stream);
    }

    private async Task DownCheckExcel()
    {
        var Stream = await Import.GetExcelCheckData();
        if (Stream is not null) await DownloadService.DownloadFromStreamAsync($"{ExcelTempName}检验结果.xlsx", Stream);
    }

    private async Task CheckExcel()
    {
        if (string.IsNullOrWhiteSpace(DataCheckUrl))
        {
            await MessageService.Warning("请输入数据检验地址");
            return;
        }
        ExcelToDataBaseStatus = await Import.CheckExcelData(DataCheckUrl!);
        await Table.QueryAsync();
    }

    private async Task ExcelToDataBase()
    {
        if (string.IsNullOrWhiteSpace(DataImportUrl))
        {
            await MessageService.Warning("请输入数据导入地址");
            return;
        }
        if (!ExcelToDataBaseStatus)
        {
            await MessageService.Warning("数据检验成功后重试");
            return;
        }
        if (await Import.ImportExcelData(DataImportUrl!))
        {
            IsShowTable = false;
            await Modal!.Toggle();
        }
    }
}
